package com.wocai.jrt.orgadmin.investor.action;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vteba.tx.jdbc.sequence.HexademicalKeyGenerator;
import com.vteba.utils.common.PropUtils;
import com.vteba.utils.common.PropsUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.model.Org;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.employee.service.spi.OrgService;
import com.wocai.jrt.orgadmin.investor.bean.EmpBreifBean;
import com.wocai.jrt.orgadmin.investor.bean.EmpGroupTreeBean;
import com.wocai.jrt.orgadmin.investor.bean.GroupBean;
import com.wocai.jrt.orgadmin.investor.bean.InvestorReqBean;
import com.wocai.jrt.orgadmin.investor.bean.InvestorResBean;
import com.wocai.jrt.orgadmin.investor.bean.MatchReqBean;
import com.wocai.jrt.orgadmin.investor.bean.RelationReqBean;
import com.wocai.jrt.orgadmin.investor.bean.RelationResBean;
import com.wocai.jrt.orgadmin.investor.bean.ResultBean;
import com.wocai.jrt.orgadmin.investor.model.Investor;
import com.wocai.jrt.orgadmin.investor.model.RiskDisclosure;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorService;
import com.wocai.jrt.orgadmin.investor.service.spi.RiskDisclosureService;
import com.wocai.jrt.orgadmin.orders.bean.OrderReqBean;
import com.wocai.jrt.orgadmin.orders.bean.OrderResBean;
import com.wocai.jrt.orgadmin.orders.model.Orders;
import com.wocai.jrt.orgadmin.orders.service.spi.OrdersService;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.ImgType;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.SmsUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;
import com.wocai.jrt.orgadmin.utils.WPS2PDFUtils;
import com.wocai.jrt.orgadmin.utils.WordUtils;

/**
 * 投资人控制器
 * 
 * @author zhangyz
 * @date 2015-8-4 20:08:33
 */
@Controller
@RequestMapping("/investor")
public class InvestorAction extends GenericAction<Investor> {
	@Inject
	private InvestorService investorServiceImpl;
	@Inject
	private EmployeeService employeeServiceImpl;
	@Inject
	private HexademicalKeyGenerator hexademicalKeyGenerator;
	@Inject
	private OrgService orgServiceImpl;
	@Inject
	private OrdersService ordersServiceImpl;
	@Inject
	private RiskDisclosureService riskDisclosureServiceImpl;
	@Inject
	private ProductService productServiceImpl;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(InvestorAction.class);

	public static final String IMAGES_URL = PropUtils.get("images.url");

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		// binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获得消息List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 消息List
	 */
	@RequestMapping("/list")
	public String list(Investor model, Map<String, Object> maps) {
		try {
			// 获取机构下所有组别列表
			GroupBean groupBean = new GroupBean();
			groupBean.setOrgId(UserUtils.getOrgId());
			List<GroupBean> groupList = investorServiceImpl.getGroupList(groupBean);
			List<Investor> list = investorServiceImpl.pagedList(model);
			maps.put("list", list);
			maps.put("groupList", groupList);
		} catch (Exception e) {
			LOGGER.error("get Investor list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "investor/list";
	}

	/**
	 * 获取理财师团队树tree
	 * 
	 * @return EmpGroupTreeBean
	 */
	@ResponseBody
	@RequestMapping("/empTree")
	public EmpGroupTreeBean empTree() {
		EmpGroupTreeBean empGroupTree = new EmpGroupTreeBean();
		try {
			// 获取机构下理财师团队树
			empGroupTree = investorServiceImpl.empTree(UserUtils.getOrgId());
		} catch (Exception e) {
			LOGGER.error("build authorities tree error, msg=[{}].", e.getMessage());
		}
		return empGroupTree;
	}

	/**
	 * 获得投资人List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 投资人List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody Investor model) {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Date date = model.getEndTime();
			if (date != null) {
				model.setEndTime(new DateTime(date).plusHours(23).plusMinutes(59).plusSeconds(59)
						.toDate());
			}
			// 获取当前机构ID
			model.setOrgId(UserUtils.getOrgId());
			String groups = model.getEmpGroup();
			if (groups != null && !groups.equals("")) {
				List<String> groupList = new ArrayList<String>();
				String[] str = groups.split(",");
				for (String string : str) {
					groupList.add(string);
				}
				model.setEmpGroupList(groupList);
			}
			model.setOrderBy("register_time desc");
			List<InvestorResBean> list = investorServiceImpl.queryMyList(model);
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = investorServiceImpl.queryMyList(model).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Investor query success.");
			}
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("Investor query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 获得投资人List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 投资人List
	 */
	@ResponseBody
	@RequestMapping("/queryFactor")
	public JsonBean queryFactor(@RequestBody InvestorReqBean reqBean) {
		JsonBean bean = new JsonBean();
		try {
			if (reqBean.getEndTime() != null) {
				reqBean.setEndTime(new DateTime(reqBean.getEndTime()).plusHours(23).plusMinutes(59)
						.plusSeconds(59).toDate());
			}
			List<Investor> list = investorServiceImpl.queryFactor(reqBean);
			bean.setCode(1);
			bean.setData(list);
			bean.setMessage("检索投资人成功");
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage("检索投资人失败");
			LOGGER.error("queryFactor Investor list error, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}

	/**
	 * 投资人头像新增上传
	 * 
	 * @param id
	 *            参数id
	 * @return 投资人实体
	 */
	@ResponseBody
	@RequestMapping("/avatarnew")
	public ResultBean avatarnew(@RequestParam("__avatar1") MultipartFile file,
			@RequestParam("id") String id) {
		ResultBean result = new ResultBean();
		try {
			// 判断文件大小
			if (file.getSize() > (1024 * 1024 * 1024 * 2L)) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像文件不能大于2M！");
				return result;
			}
			LOGGER.info("request file upload, filename=[{}]", file.getOriginalFilename());
			// 上传头像
			String filePath = MyFileUtils.uploadImg(file, ImgType.values()[0], ".jpeg");
			Investor investor = new Investor();
			investor.setId(id);
			investor.setAvatar(filePath);
			int i = investorServiceImpl.updateById(investor);
			if (i != 1) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像保存出错！");
				// 删除当前保存的头像
				filePath = IMAGES_URL + filePath;
				File files = new File(filePath);
				MyFileUtils.deleteFileDir(files);
				if (null != file) {
					files.delete();
				}
				return result;
			}
			LOGGER.info("upload file success, filePath=[{}]", filePath);
			// 封装result
			result.setCode(5);
			result.setType(0);
			result.setSuccess(true);
			result.setSourceUrl(filePath);
			result.setMsg("upload file success");
			// JSON.toJSONString(jsonBean);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("upload file error, error=[{}]", e.getMessage());
			result.setCode(5);
			result.setType(3);
			result.setSuccess(false);
			result.setMsg("upload file error");
		}
		return result;
	}

	/**
	 * 投资人头像修改上传
	 * 
	 * @param id
	 *            参数id
	 * @return 投资人实体
	 */
	@ResponseBody
	@RequestMapping("/avatarup")
	public ResultBean avatarup(@RequestParam("__avatar1") MultipartFile file,
			@RequestParam("id") String id, @RequestParam("oldPath") String oldPath) {
		ResultBean result = new ResultBean();
		try {
			// 判断文件大小
			if (file.getSize() > (1024 * 1024 * 1024 * 2L)) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像文件不能大于2M！");
				return result;
			}

			LOGGER.info("request file upload, filename=[{}]", file.getOriginalFilename());
			// 上传头像
			String filePath = MyFileUtils.uploadImg(file, ImgType.values()[0], ".jpeg");
			Investor investor = new Investor();
			investor.setId(id);
			investor.setAvatar(filePath);
			int i = investorServiceImpl.updateById(investor);
			if (i != 1) {
				result.setCode(4);
				result.setSuccess(false);
				result.setMsg("头像保存出错！");
				// 删除当前保存的头像
				filePath = filePath.substring(0, filePath.lastIndexOf("/"));
				File files = new File(filePath);
				MyFileUtils.deleteFileDir(files);
				if (null != file) {
					files.delete();
				}
				return result;
			} else if (null != oldPath && !StringUtils.isBlank(oldPath)) {
				// 删除旧头像
				oldPath = IMAGES_URL + oldPath;
				File files = new File(oldPath);
				MyFileUtils.deleteFileDir(files);
				if (null != file) {
					files.delete();
				}
			}
			LOGGER.info("upload file success, filePath=[{}]", filePath);
			// 封装result
			result.setCode(5);
			result.setType(0);
			result.setSuccess(true);
			result.setSourceUrl(filePath);
			result.setMsg("upload file success");
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("upload file error, error=[{}]", e.getMessage());
			result.setCode(5);
			result.setType(3);
			result.setSuccess(false);
			result.setMsg("upload file error");
		}
		return result;
	}

	/***
	 * 下载头像img
	 * 
	 * @param path
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/downImg")
	public JsonBean downImg(String path, HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 发起请求的参数
			LOGGER.info("download img , url=[{}]", path);
			MyFileUtils.downloadFile(path, response);
			jsonBean.setCode(1);
			jsonBean.setMessage("下载头像成功!");
		} catch (Exception e) {
			LOGGER.error("download img error, error=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("下载头像失败!");
		}
		return jsonBean;
	}

	/**
	 * 根据Id获得投资人实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 投资人实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public Investor get(String id) {
		Investor model = investorServiceImpl.get(id);
		return model;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add(Map<String, Object> maps) {
		GroupBean groupBean = new GroupBean();
		groupBean.setOrgId(UserUtils.getOrgId());
		// 获取当前机构下所有投资人分组信息
		List<GroupBean> list = investorServiceImpl.getGroupList(groupBean);
		maps.put("groupList", list);
		maps.put("investorId", ObjectId.get().toString());
		return "investor/add";
	}

	/**
	 * 投资人数据校验
	 * 
	 * @param model
	 * @return boolean
	 */
	@ResponseBody
	@RequestMapping("/check")
	public boolean check(Investor model, Integer type) {
		if (type == null) {
			return false;
		}
		model.setOrgId(UserUtils.getOrgId());
		// 如果投资人id不为空，则是修改投资人详情
		String investorId = model.getId();
		if (StringUtils.isNotBlank(investorId)) {
			Investor investor = investorServiceImpl.get(investorId);
			if (investor == null) {
				return false;
			}
			int result = investorServiceImpl.countBy(model);
			// 修改投资人详情,查询到多条信息,返回错误
			if (result > 1) {
				return false;
				// 修改投资人详情,查询到该人信息,但不是投资人之前的旧信息,返回错误
			} else if (result == 1) {
				if (type == 1) {
					if (!model.getMobile().equals(investor.getMobile())) {
						return false;
					}
				} else if (type == 2) {
					if (!model.getIdcard().equals(investor.getIdcard())) {
						return false;
					}
				}
			}
		} else {
			// 新增投资人判断信息是否已经存在
			int result = investorServiceImpl.countBy(model);
			// 该投资人信息已经存在
			if (result >= 1) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(@RequestBody @Valid Investor model, BindingResult errors) {
		JsonBean bean = new JsonBean();
		try {
			if (errors.hasErrors()) {
				bean.setCode(0);
				bean.setMessage("参数错误");
				return bean;
			}
			String mobile = model.getMobile();
			if (!Pattern.compile("^[1][3,4,5,8][0-9]{9}$").matcher(mobile).matches()
					&& !Pattern.compile("[0]{1}[0-9]{2,3}[0-9]{7,8}$").matcher(mobile).matches()) {
				bean.setCode(0);
				bean.setMessage("联系电话输入有误！");
				return bean;
			}
			// 获取机构代码
			String orgId = UserUtils.getOrgId();
			String idcard = model.getIdcard();
			// 根据手机号码查询当前投资人是否已经存在
			Investor temp = new Investor();
			temp.setOrgId(orgId);
			temp.setMobile(mobile);
			temp.setRegisterTime(null);
			Investor vestor = investorServiceImpl.unique(temp);
			if (null != vestor) {
				bean.setCode(0);
				bean.setMessage("当前手机号码已经被注册");
				return bean;
			}
			// 根据身份证号码查询当前投资人是否已经存在
			if (idcard != null) {
				temp.setMobile(null);
				temp.setIdcard(idcard);
				Investor vestor_second = investorServiceImpl.unique(temp);
				if (null != vestor_second) {
					bean.setCode(0);
					bean.setMessage("当前证件号码已经被注册");
					return bean;
				}
			}
			model.setIdType(model.getIdType());
			model.setOrgId(orgId);
			model.setId(model.getId());
			model.setRegisterTime(new Date());
			model.setDeleted(false);
			model.setSource(1);//投资人注册来源 1-pc 2-pad 3-微官网
			model.setInvitationCode(hexademicalKeyGenerator.next());
			int result = investorServiceImpl.save(model);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage("投资人添加成功！");
				// 修改投资人分组
				investorServiceImpl.modifyGroup(model);
			} else {
				bean.setCode(0);
				bean.setMessage("投资人添加失败！");
			}
		} catch (Exception e) {
			LOGGER.error("doAdd Investor list error, errorMsg=[{}].", e.getMessage());
			bean.setMessage("投资人添加失败！" + e.getMessage());
		}
		return bean;
	}

	/**
	 * 查看投资人详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 投资人详情页
	 */
	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			Investor model = new Investor();
			model = investorServiceImpl.get(id);
			String employeeId = model.getEmployeeId();
			if (!StringUtils.isBlank(employeeId)) {
				Employee emp = employeeServiceImpl.get(employeeId);
				if (emp != null) {
					model.setEmployeeName(emp.getName());
				}
			}
			// 获取投资人所在分组列表
			List<GroupBean> invesGroupList = investorServiceImpl.getInvestorGroupList(model);
			maps.put("groupList", invesGroupList);
			maps.put("model", model);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			return "common/error";
		}
		return "investor/detail";
	}

	/**
	 * 查询机构下的理财师。
	 * 
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@ResponseBody
	@RequestMapping("/employee/{employeeKey}")
	public List<EmpBreifBean> employee(@PathVariable("employeeKey") String employeeKey) {
		JsonBean bean = new JsonBean();
		try {
			// 查询该机构下所有理财师列表
			List<EmpBreifBean> eBean = investorServiceImpl.getOrgEmployeeList(UserUtils.getOrgId(),
					employeeKey);
			return eBean;
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage("获取机构理财师列表失败:" + e.getMessage());
			LOGGER.error("get Investor list error, errorMsg=[{}].", e.getMessage());
		}
		return null;
	}

	/**
	 * 获得联系记录列表
	 * 
	 * @param model
	 *            参数
	 * @return 联系记录List
	 */
	@ResponseBody
	@RequestMapping("/queryDetail")
	public Map<String, Object> queryDetail(@RequestBody Investor model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if (model.getEndTime() != null) {
				model.setEndTime(new DateTime(model.getEndTime()).plusHours(23).plusMinutes(59)
						.plusSeconds(59).toDate());
			}
			List<RelationResBean> list = investorServiceImpl.queryRelation(model);

			// 统计的时候，不需要分页
			model.setStart(null);
			long totalRecord = list.size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("investorDetail query success.");
			}

			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("investorDetail query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			Investor model = new Investor();
			model.setId(id);
			model = investorServiceImpl.get(model.getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = model.getBirthday();
			if (date != null) {
				model.setBirthdayString(sdf.format(date));
			}
			// 获取所有投资人所不在分组列表
			Investor v = new Investor();
			v.setId(id);
			v.setOrgId(UserUtils.getOrgId());
			List<GroupBean> groupList = investorServiceImpl.getOutGroupList(v);
			// 获取投资人所在分组列表
			List<GroupBean> invesGroupList = investorServiceImpl.getInvestorGroupList(v);
			maps.put("groupList", groupList);
			maps.put("invesGroupList", invesGroupList);
			maps.put("model", model);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("edit investor error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "investor/edit";
	}

	/**
	 * 执行实际的修改操作
	 * 
	 * @param model
	 *            要修改的数据
	 */
	@ResponseBody
	@RequestMapping("/doEdit")
	public JsonBean doEdit(@RequestBody @Valid Investor model, BindingResult errors) {
		JsonBean bean = new JsonBean();
		try {
			if (errors.hasErrors()) {
				bean.setCode(0);
				bean.setMessage("输入参数错误");
				return bean;
			}
			int result = investorServiceImpl.updateInvestor(model);
			// 修改投资人分组
			model.setOrgId(UserUtils.getOrgId());
			investorServiceImpl.modifyGroup(model);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage("投资人修改成功！");
			} else {
				bean.setCode(0);
				bean.setMessage("投资人修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("doEdit Investor list error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(e.getMessage());
		}
		return bean;
	}

	/**
	 * 跳转联系记录列表
	 * 
	 * @param model
	 * @return 操作结果信息
	 */
	@RequestMapping("/relation/{id}")
	public String relation(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			Investor model = new Investor();
			model.setId(id);
			List<Investor> list = investorServiceImpl.pagedList(model);
			maps.put("list", list);
			maps.put("model", model);
		} catch (Exception e) {
			LOGGER.error("get relation list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "investor/relation";
	}

	/**
	 * 获得投资人联系记录列表
	 * 
	 * @param model
	 *            参数
	 * @return 联系记录List
	 */
	@ResponseBody
	@RequestMapping("/queryRela")
	public Map<String, Object> queryRela(@RequestBody Investor model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if (model.getEndTime() != null) {
				model.setEndTime(new DateTime(model.getEndTime()).plusHours(23).plusMinutes(59)
						.plusSeconds(59).toDate());
			}
			model.setOrderBy("visit_time desc");
			List<RelationResBean> list = investorServiceImpl.queryRelation(model);

			// 统计的时候，不需要分页
			model.setStart(null);
			long totalRecord = list.size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Investor query success.");
			}

			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("relation query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 新增联系记录
	 * 
	 * @param RelationReqBean
	 *            relationReqBean
	 * @return JsonBean
	 */
	@ResponseBody
	@RequestMapping("/addRela")
	public JsonBean addRela(@RequestBody RelationReqBean relationReqBean) {
		JsonBean bean = new JsonBean();
		try {
			relationReqBean.setVisitTime(new Date());
			relationReqBean.setId(ObjectId.get().toString());
			relationReqBean.setEmployeeName(UserUtils.getUser().getName());
			relationReqBean.setEmployeeId(UserUtils.getUserId());
			int result = investorServiceImpl.addRela(relationReqBean);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage("联系记录添加成功");
			} else {
				bean.setCode(0);
				bean.setMessage("联系记录添加失败");
			}
		} catch (Exception e) {
			LOGGER.error("addRela employee error, msg=[{}]", e.getMessage());
			bean.setMessage("联系记录添加失败：" + e.getMessage());
		}
		return bean;
	}

	/**
	 * 给投资人分配理财师
	 * 
	 * @param MatchReqBean
	 *            matchReqBean
	 * @return boolean
	 */
	@ResponseBody
	@RequestMapping("/allotEmp")
	public JsonBean allotEmp(@RequestBody MatchReqBean matchReqBean) {
		JsonBean bean = new JsonBean();
		try {
			boolean bool = investorServiceImpl.allotEmp(matchReqBean);
			if (bool) {
				bean.setMessage("分配理财师成功");
			}
		} catch (Exception e) {
			LOGGER.error("allotEmp employee error, msg=[{}]", e.getMessage());
			bean.setMessage("分配理财师失败：" + e.getMessage());
		}
		return bean;
	}

	/**
	 * 获得投资人组别List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 消息List
	 */
	@RequestMapping("/group")
	public String group(Investor model, Map<String, Object> maps) {
		try {
			// 获取机构下所有组别列表
			GroupBean groupBean = new GroupBean();
			groupBean.setOrgId(UserUtils.getOrgId());
			List<GroupBean> groupList = investorServiceImpl.getGroupList(groupBean);
			List<Investor> list = investorServiceImpl.pagedList(model);
			maps.put("list", list);
			maps.put("groupList", groupList);
		} catch (Exception e) {
			LOGGER.error("get Investor list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "investor/group";
	}

	/**
	 * 获得投资人分组List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 投资人List
	 */
	@ResponseBody
	@RequestMapping("/queryGroup")
	public Map<String, Object> queryGroup(@RequestBody GroupBean gBean) {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			gBean.setOrgId(UserUtils.getOrgId());
			List<GroupBean> list = investorServiceImpl.getGroupList(gBean);
			// 统计的时候，不需要分页
			gBean.setPage(null);
			long totalRecord = investorServiceImpl.getGroupList(gBean).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Investor query success.");
			}
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("Investor query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 新增投资人分组
	 * 
	 * @param GroupBean
	 *            gBean
	 * @return JsonBean
	 */
	@ResponseBody
	@RequestMapping("/addGroup")
	public JsonBean addGroup(@RequestBody GroupBean gBean) {
		JsonBean bean = new JsonBean();
		try {
			gBean.setId(ObjectId.get().toString());
			gBean.setNumber(new Integer(0));
			gBean.setOrgId(UserUtils.getOrgId());
			// 判断当前分组名是否已经存在
			GroupBean g = new GroupBean();
			g.setName(gBean.getName().trim());
			g.setOrgId(UserUtils.getOrgId());
			List<GroupBean> list = investorServiceImpl.getGroupList(g);
			if (list.size() > 0) {
				bean.setMessage("新增分组失败,该分组名已存在");
				bean.setCode(0);
				return bean;
			}
			int result = investorServiceImpl.addGroup(gBean);
			if (result == 1) {
				bean.setMessage("新增投资人分组成功");
				// 获取机构下所有组别列表
				GroupBean groupBean = new GroupBean();
				groupBean.setOrgId(UserUtils.getOrgId());
				List<GroupBean> groupList = investorServiceImpl.getGroupList(groupBean);
				bean.setData(groupList);
				bean.setCode(1);
			} else {
				bean.setMessage("新增投资人分组失败");
				bean.setCode(0);
			}
		} catch (Exception e) {
			LOGGER.error("allotEmp employee error, msg=[{}]", e.getMessage());
			bean.setMessage("新增投资人分组失败：" + e.getMessage());
			bean.setCode(0);
		}
		return bean;
	}

	/**
	 * 修改投资人分组名
	 * 
	 * @param GroupBean
	 *            gBean
	 * @return JsonBean
	 */
	@ResponseBody
	@RequestMapping("/modifyGroup")
	public JsonBean modifyGroup(@RequestBody GroupBean gBean) {
		JsonBean bean = new JsonBean();
		try {
			gBean.setOrgId(UserUtils.getOrgId());
			// 判断当前分组名是否已经存在
			GroupBean g = new GroupBean();
			g.setName(gBean.getName());
			List<GroupBean> list = investorServiceImpl.getGroupList(g);
			if (list.size() > 0) {
				bean.setMessage("修改分组失败,该分组名已存在");
				return bean;
			}
			int result = investorServiceImpl.modifyGroup(gBean);
			if (result == 1) {
				bean.setMessage("修改投资人分组成功");
			} else {
				bean.setMessage("修改投资人分组失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("allotEmp employee error, msg=[{}]", e.getMessage());
			bean.setMessage("修改投资人分组失败：" + e.getMessage());
		}
		return bean;
	}

	/**
	 * 删除投资人分组
	 * 
	 * @param GroupBean
	 *            gBean
	 * @return JsonBean
	 */
	@ResponseBody
	@RequestMapping("/delGroup")
	public JsonBean delGroup(@RequestBody GroupBean gBean) {
		JsonBean bean = new JsonBean();
		try {
			if (gBean.getId() == null) {
				bean.setMessage("参数异常");
				return bean;
			}
			int result = investorServiceImpl.delGroup(gBean);
			if (result == 1) {
				bean.setMessage("删除投资人分组成功");
			} else {
				bean.setMessage("删除投资人分组失败");
			}
		} catch (Exception e) {
			LOGGER.error("allotEmp employee error, msg=[{}]", e.getMessage());
			bean.setMessage("删除投资人分组失败：" + e.getMessage());
		}
		return bean;
	}

	/**
	 * 发送邀请码
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 投资人详情页
	 */
	@ResponseBody
	@RequestMapping("/sendInvitationCode/{id}")
	public JsonBean sendInvitationCode(@PathVariable("id") String id, Map<String, Object> maps) {
		JsonBean json = new JsonBean();
		try {
			Investor model = new Investor();
			model = investorServiceImpl.get(id);
			if (null == model) {
				json.setCode(0);
				json.setMessage("投资人不存在！");
				return json;
			}
			String invitationCode = model.getInvitationCode();
			if (null == invitationCode) {
				// 更新投资人邀请码
				invitationCode = hexademicalKeyGenerator.next();
				// 保存投资人邀请码
				Investor paramT = new Investor();
				paramT.setId(id);
				paramT.setInvitationCode(invitationCode);
				investorServiceImpl.updateById(paramT);
			}
			// 发送短信给投资人
			String mobile = model.getMobile();
			if (null != mobile) {
				if (mobile.startsWith("1")) {
					String content = "邀请码：" + invitationCode;
					String result = SmsUtils.send(mobile, content);
					if (result.startsWith("true")) {
						json.setCode(1);
						json.setMessage("邀请码发送成功！");
					} else {
						json.setCode(0);
						json.setMessage(result);
					}
				} else {
					json.setCode(0);
					json.setMessage(model.getName() + "的联系电话非手机，请修改为手机号码!");
				}
			} else {
				json.setCode(0);
				json.setMessage("投资人没有电话号码！");
			}
		} catch (Exception e) {
			LOGGER.error("sendInvitationCode error, msg=[{}]", e.getMessage());
			json.setCode(0);
			json.setMessage("发送邀请码失败！");
		}
		return json;
	}

	/**
	 * 获得投资人组别List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 消息List
	 */
	@RequestMapping("/riskDisclosure")
	public String riskDisclosure(Investor model, Map<String, Object> maps) {
		try {
			// 获取机构下所有组别列表
			GroupBean groupBean = new GroupBean();
			groupBean.setOrgId(UserUtils.getOrgId());
			List<GroupBean> groupList = investorServiceImpl.getGroupList(groupBean);
			List<Investor> list = investorServiceImpl.pagedList(model);

			Org org = orgServiceImpl.get(UserUtils.getOrgId());
			//获取当前机构所有风险揭示书
			RiskDisclosure rd = new RiskDisclosure();
			rd.setOrgId(UserUtils.getOrgId());
			List<RiskDisclosure> rList = riskDisclosureServiceImpl.pagedList(rd);
			maps.put("list", list);
			maps.put("groupList", groupList);
			maps.put("rList", rList);
			maps.put("riskDisclosure", org.getRiskDisclosure());
		} catch (Exception e) {
			LOGGER.error("get Investor list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "investor/riskDisclosure";
	}
	
	
	/**
	 * 获得投资人组别List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 消息List
	 */
	@RequestMapping("/riskManager")
	public String riskManager(Map<String, Object> maps) {
		try {
			// 获取机构下所有风险揭示书列表
			RiskDisclosure rd = new RiskDisclosure();
			rd.setOrgId(UserUtils.getOrgId());
			List<RiskDisclosure> list = riskDisclosureServiceImpl.pagedList(rd);

			maps.put("list", list);
			maps.put("riskDisclosureList",list);
		} catch (Exception e) {
			LOGGER.error("get Investor list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "investor/riskManager";
	}
	
	/**
	 * 风险揭示书列表查询
	 * @param model
	 *            参数
	 * @return 订单List
	 */
	@ResponseBody
	@RequestMapping(value = "/riskListQuery", method = RequestMethod.POST)
	public Map<String, Object> riskListQuery(@RequestBody RiskDisclosure rd) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			rd.setOrgId(UserUtils.getOrgId());
			rd.setOrderBy("upload_time desc");
			List<RiskDisclosure> list = riskDisclosureServiceImpl.pagedList(rd);

			// 统计的时候，不需要分页
			rd.setPage(null);
			long totalRecord = riskDisclosureServiceImpl.pagedList(rd).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("riskListQuery query success.");
			}

			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("order query error, msg=[{}]", e.getMessage());
		}
		return result;
	}
	/**
	 * 上传风险揭示书
	 * @param riskDisclosureFile
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/upload")
	public JsonBean upload(MultipartFile riskDisclosureFile) {
		JsonBean jsonBean = new JsonBean();
		try {

			// 验证file
			jsonBean = validFile(riskDisclosureFile);

			if (jsonBean.getCode() != 1) {
				jsonBean.setCode(0);
				jsonBean.setMessage("Fail to upload image/file");
				LOGGER.error("Fail to upload image/file");

				return jsonBean;
			}
			jsonBean.setMessage(SUCCESS); // 成功
			LOGGER.info("Upload image/file success.");
			//更新风险揭示书
			RiskDisclosure rd = new RiskDisclosure();
			rd.setId(ObjectId.get().toString());
			rd.setName(riskDisclosureFile.getOriginalFilename());
			rd.setUploadTime(new Date());
			rd.setOrgId(UserUtils.getOrgId());
			rd.setUrl(((Org)jsonBean.getData()).getRiskDisclosure());
			riskDisclosureServiceImpl.save(rd);
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("upload riskDisclosureFile falure");
			LOGGER.error("upload riskDisclosureFile falure, msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}
	
	/**
	 * 修改风险揭示书
	 * @param riskDisclosureFile
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/modifyDisclosureFile")
	public JsonBean modifyDisclosureFile(MultipartFile riskDisclosureFile,String id) {
		JsonBean jsonBean = new JsonBean();
		try {

			// 验证file
			jsonBean = validFile(riskDisclosureFile);

			if (jsonBean.getCode() != 1) {
				jsonBean.setCode(0);
				jsonBean.setMessage("Fail to upload image/file");
				LOGGER.error("Fail to upload image/file");

				return jsonBean;
			}
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS); // 成功
			LOGGER.info("Upload image/file success.");
			//更新风险揭示书
			RiskDisclosure rd = new RiskDisclosure();
			rd.setId(id);
			rd.setName(riskDisclosureFile.getOriginalFilename());
			rd.setUploadTime(new Date());
			rd.setUrl(((Org)jsonBean.getData()).getRiskDisclosure());
			riskDisclosureServiceImpl.updateById(rd);
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("upload riskDisclosureFile falure");
			LOGGER.error("upload riskDisclosureFile falure, msg = [{}]", e.getMessage());
		}
		return jsonBean;
	}
	
	private JsonBean validFile(MultipartFile riskDisclosureFile) throws IOException {
		JsonBean jsonBean = new JsonBean();
		Org oldModel = orgServiceImpl.get(UserUtils.getOrgId());
		Org newModel = new Org();
		newModel.setId(oldModel.getId());

		if (null != riskDisclosureFile) {
			if (!StringUtils.isBlank(oldModel.getRiskDisclosure())) {
				File oldContactFile = new File(oldModel.getRiskDisclosure());
				File oldContactParent = oldContactFile.getParentFile();
				if (oldContactFile.exists()) {
					oldContactFile.delete();
					oldContactParent.delete();
				}
			}

			String riskDisclosureFilePath = MyFileUtils.uploadFile(riskDisclosureFile,
					MyFileUtils.FILE_TYPE);

			newModel.setRiskDisclosure(riskDisclosureFilePath);
		}

		if (null != riskDisclosureFile) {
			orgServiceImpl.updateById(newModel);
		}

		jsonBean.setCode(1);
		jsonBean.setData(newModel);
		return jsonBean;
	}
	
	/**
	 * 风险揭示书下载效果预览
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/downloadEffect")
	public JsonBean downloadEffect(HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();
		try {
			String filePath = orgServiceImpl.get(UserUtils.getOrgId()).getRiskDisclosure();

			// 发起请求的参数
			LOGGER.info("request downloadEffect, url=[{}]", filePath);

			if (StringUtils.isBlank(filePath)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("downloadEffect error with filePath is blank");
				LOGGER.error("downloadEffect error with filePath is blank");
				return jsonBean;
			}

			String destPath = null;

			if (filePath.toLowerCase().endsWith(".docx")) {
				Map<String, String> map = new HashMap<String, String>();
				// 基金全称
				map.put("FundFullName", "杭州中金通钻石1号混合型证券投资基金");

				// 投资人签名，这里是图片路径
				String investorSignName = PropsUtils.get("contact_template_image");
				map.put("InvestorSignName", investorSignName);
				LOGGER.info("set investorSign path success, investorSignPath=[{}]",
						investorSignName);

				// 签单时间
				String signTime = new SimpleDateFormat("yyyy年MM月dd日").format(new Date());
				map.put("SignTime", signTime);
				LOGGER.info("create signTime success, signTime=[{}]", signTime);
				
				map.put("[", "");
				map.put("]", "");

				// String srcPath = "D:\\word_test\\word_test.docx";
				String filename = new File(filePath).getName();

				String docxPath = MyFileUtils.getFilePath(filename, MyFileUtils.DOC_TYPE);
				WordUtils.searchAndReplace(filePath, docxPath, map);
				LOGGER.info("replace docx success");

				destPath = MyFileUtils.getFilePath(filename.replace(".docx", "预览.pdf"),
						MyFileUtils.PDF_TYPE);
				WPS2PDFUtils.word2PDF(docxPath, destPath);
				LOGGER.info("convert docx to pdf success");
			}

			MyFileUtils.downloadFileByPath(destPath, response);

			File effectFile = new File(destPath);
			if (effectFile.exists()) {
				File parent = effectFile.getParentFile();
				effectFile.delete();
				parent.delete();
			}

			// 封装jsonBean
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("downloadEffect error");
			LOGGER.error("downloadEffect error, error=[{}]", e.getMessage());
		}

		return jsonBean;
	}
	
	/**
	 * 风险揭示书下载效果预览
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkRiskDisclosure")
	public JsonBean checkRiskDisclosure() {
		JsonBean jsonBean = new JsonBean();
		try {
			String filePath = orgServiceImpl.get(UserUtils.getOrgId()).getRiskDisclosure();

			if (StringUtils.isBlank(filePath)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("downloadEffect error with filePath is blank");
				LOGGER.error("downloadEffect error with filePath is blank");
				return jsonBean;
			}
			// 封装jsonBean
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("checkRiskDisclosure error");
			LOGGER.error("downloadEffect error, error=[{}]", e.getMessage());
		}
		return jsonBean;
	}
	
	/**
	 * 生成风险揭示书
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/createRiskDisclosure/{orderId}")
	public void createRiskDisclosure(@PathVariable("orderId") String orderId,HttpServletResponse response){
		// 用户（投资人）各自合并签名后的揭示书路径
		String userRiskDisclosure = null;
		try {
			// 获取订单详情
			Orders orderParam = new Orders();
			orderParam.setOrderId(orderId);
			Orders order = ordersServiceImpl.unique(orderParam);

			// 获取机构详情
			Org org = orgServiceImpl.get(order.getOrgId());

			// 风险揭示书原件
			String riskDisclosure = org.getRiskDisclosure();
			if (!StringUtils.isBlank(riskDisclosure)) {
				if (riskDisclosure.toLowerCase().endsWith(".docx")) {

					Map<String, String> map = new HashMap<String, String>();

					// 基金全称
					map.put("FundFullName", order.getProductName());

					// 投资人签名，这里是图片路径
					String investorSignName = PropsUtils.get("images.url") + order.getContactSignUser();
					map.put("InvestorSignName", investorSignName);
					LOGGER.info("set investorSign path success, investorSignPath=[{}]",
							investorSignName);

					// 签单时间(下单时间)
					String signTime = new SimpleDateFormat("yyyy年MM月dd日").format(order.getOrderTime());
					map.put("SignTime", signTime);
					LOGGER.info("create signTime success, signTime=[{}]", signTime);

					map.put("[", "");
					map.put("]", "");

					// 生成中间文件路径，中间文件不会被删除，作为备份
					String filename = new File(riskDisclosure).getName();
					String docxPath = MyFileUtils.getFilePath(filename, MyFileUtils.DOC_TYPE);

					// 生成中间文件，即替换占位符生成新的docx文件，注：contactPath带占位符合同路径，docxPath替换后中间文件路径
					WordUtils.searchAndReplace(riskDisclosure, docxPath, map);
					LOGGER.info("replace contact file success, contactPath=[{}], docxPath=[{}]",
							riskDisclosure, docxPath);
					

					String investorName = investorServiceImpl.get(order.getInvestorId()).getName();

					// 生成最终的pdf文件路径
					userRiskDisclosure = MyFileUtils.getFilePath(
							filename.replace(".docx", "_【" + investorName + "】.pdf"),
							MyFileUtils.PDF_TYPE);

					// 生成最终的pdf文件，即将中间文件docx转换成pdf文件即可,userContactPath:目标文件路径
					WPS2PDFUtils.word2PDF(docxPath, userRiskDisclosure);
					LOGGER.info("convert word to pdf success, docxPath=[{}], userContactPath=[{}]",
							docxPath, userRiskDisclosure);

					// 更新订单合同编号
					Orders orderData = new Orders();

					// 这里不是orderId而是id
					orderData.setId(order.getId());
					orderData.setRiskDisclosure(userRiskDisclosure);
					ordersServiceImpl.updateById(orderData);
					response.setCharacterEncoding("utf-8");
					response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(userRiskDisclosure, "UTF-8"));
					response.setContentType("application/octet-stream; charset=utf-8");
					MyFileUtils.downloadFile(userRiskDisclosure, response);
					LOGGER.info(
							"update order orderContactNum success,  orderId=[{}], userRiskDisclosure=[{}]",
							orderId, userRiskDisclosure);
				} else {
					LOGGER.error("not support other file format but docx, userContactPath=[{}]",
							userRiskDisclosure);
				}
			}
		} catch (Exception e) {
			LOGGER.error("create RiskDisclosure error,due to =[{}]",e.getMessage());
		}
	}
	
	/**
	 * 风险揭示书查询
	 * @param model
	 *            参数
	 * @return 订单List
	 */
	@ResponseBody
	@RequestMapping(value = "/riskQuery", method = RequestMethod.POST)
	public Map<String, Object> query(@RequestBody OrderReqBean model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			model.setOrderBy("FIELD(o.state, 5) ASC,order_time desc");
			Date orderEnd = model.getOrderTimeEnd();
			if (orderEnd != null) {
				DateTime date = new DateTime(orderEnd);
				date = date.plusDays(1).minusMillis(1);
				model.setOrderTimeEnd(date.toDate());
			}
			LOGGER.info("获取订单的model参数: [{}]",JSON.toJSONString(model));
			List<OrderResBean> list = ordersServiceImpl.getRiskResBeanList(model);
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = ordersServiceImpl.getRiskResBeanList(model).size();

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("order query success.");
			}
	
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("order query error, msg=[{}]", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 删除风险揭示书
	 * @param id
	 *            参数
	 * @return jsonbean
	 */
	@ResponseBody
	@RequestMapping(value = "/delRiskDisclosure/{id}")
	public JsonBean delRiskDisclosure(@PathVariable("id") String id){
		JsonBean json = new JsonBean();
		if(StringUtils.isBlank(id)){
			json.setCode(0);
			json.setMessage("参数异常!");
			LOGGER.info("delRiskDisclosure requert params error");
			return json;
		}
		try {
			RiskDisclosure rd = riskDisclosureServiceImpl.get(id);
    		RiskDisclosure params = new RiskDisclosure();
    		params.setOrgId(rd.getOrgId());
    		List<RiskDisclosure> list = riskDisclosureServiceImpl.pagedList(params);
    		if(list.size() <= 1){
    			json.setMessage("当前仅有一份风险揭示书模板，无法删除!");
    			json.setCode(0);
    			return json;
    		}
			Product p = new Product();
			p.setRiskDisclosureId(id);
			List<Product> pList = productServiceImpl.pagedList(p);
			if(pList.size() > 0){
				json.setCode(0);
				json.setMessage("风险揭示书已经关联订单或产品,无法删除!");
				LOGGER.info("delRiskDisclosure error due to has product quote");
				return json;
			}
			Orders o = new Orders();
			o.setRiskDisclosureId(id);
			List<Orders> oList = ordersServiceImpl.pagedList(o);
			if(oList.size() > 0){
				json.setCode(0);
				json.setMessage("风险揭示书已经关联订单或产品,无法删除!");
				LOGGER.info("delRiskDisclosure error due to has product quote");
				return json;
			}
			//删除风险揭示书
			int result = riskDisclosureServiceImpl.deleteById(id);
			if(result == 1){
				json.setCode(1);
				json.setMessage("风险揭示书删除成功!");
			}else{
				json.setCode(0);
				json.setMessage("风险揭示书删除失败!");
			}
		} catch (Exception e) {
			json.setCode(0);
			json.setMessage(e.getMessage());
			LOGGER.info("delRiskDisclosure error is:[{}]",e.getMessage());
		}
		return json;
	}
}
